package com.spring.web.interceptor.ehcache;

import java.lang.reflect.Method;
import java.util.List;

import net.sf.ehcache.Cache;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;

public class MethodCacheAfterAdivce implements AfterReturningAdvice, InitializingBean {

	private static final Log log = LogFactory.getLog(MethodCacheAfterAdivce.class);
	
	private Cache cache;
	
	public void setCache(Cache cache){
		this.cache = cache;
	}
	
	public MethodCacheAfterAdivce(){}
	
	@Override
	public void afterPropertiesSet() throws Exception {
		Assert.isNull(cache, "methodCacheInterceptor -- need a cache, please use setCache(cache) create it");
	}

	@Override
	public void afterReturning(Object object1, Method method, Object[] objects,
			Object object2) throws Throwable {
		String className = object2.getClass().getName();
		List list = cache.getKeys();
		if(list != null && list.size() > 0){
			for(int i=0; i<list.size(); i++){
				String cacheKey = String.valueOf(list.get(i));
				if(cacheKey.startsWith(className)){
					cache.remove(cacheKey);
					log.debug("MethodCacheAfterAdivce -- remove cache " + cacheKey);
				}
			}
		}
	}
	
}
